//
//  BlogOrUserListViewModel.swift
//  mmda
//
//  Created by 李陆涛 on 2018/8/6.
//  Copyright © 2018年 mmda. All rights reserved.
//

import UIKit

enum BlogOrUserListType {
    case allblog
    case alluser
    case auser
    case mine
}

class BlogOrUserListViewModel: NSObject {
    
//    0 全部动态，1全部盟主，2我的发帖/用户发帖（我的发帖ID为nil）
    var pageType:BlogOrUserListType = .allblog
    var userid:Int?
    
    var user:User?
    var dataSource:NSMutableArray = NSMutableArray()

    private var page:Int = 1

    var loadFinished: ((_ error: String?,_ isloadMore:Bool) -> Void)?
    
    var loadUserFinished: ((_ error: String?) -> Void)?
    
    func reloadData() {
        
        if pageType == .auser {
            
            self.getUserData()
        } else if pageType == .mine {
            
            user = AppManager.share.user
            
            loadUserFinished?(nil)
        }
        
        page = 1
        getMoreData()
    }
    
    func getMoreData() {
        
        if pageType == .alluser {
            
            NetAPI.alluser(page: page).request([User].self, dealJson: "users") {
                [weak self] response, errmsg in
                guard let `self` = self else { return }
                
                self.dealResponse(response: response, errorMsg: errmsg)
                
            }
        } else {
            
            NetAPI.allblog(uid: userid, page: page).request([Blog].self, dealJson: "blogs") {
                [weak self] response, errmsg in
                guard let `self` = self else { return }
                
                self.dealResponse(response: response, errorMsg: errmsg)
                
            }
        }
    }
    
    func getUserData() {
        
        guard let uid = userid else { return }
        
        NetAPI.auser(uid: uid).request(User.self) {
        
            [weak self] response, errmsg in
            guard let `self` = self else { return }
            
            guard let user = response as? User else {
                
                self.loadUserFinished?(errmsg)
                return
            }
            
            self.user = user
            
            self.loadUserFinished?(nil)
        }
    }
    
    private func dealResponse (response:Any?,errorMsg:String?) {
        
        guard let response = response as? [Any] else {
        
            loadFinished?(errorMsg,page == 1 ? false : true)
            
            return
        }
        
        if page == 1 {
            dataSource.removeAllObjects()
        }
        
        dataSource.addObjects(from: response)
        loadFinished?(nil,page == 1 ? false : true)
        
        page = page + 1
    }
    
}
